/*

    This file is part of Hometree.

    Hometree is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Hometree is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Hometree.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2011,2012 Roman Held

*/
#include "cvcam.h"
#include <QPixmap>
#include <QDebug>

CvCam::CvCam(const QString &aviFileName, QObject *parent)
 : QObject(parent)
{
  mCapture = cvCaptureFromAVI(aviFileName.toAscii().data());
  Q_ASSERT(mCapture);
  connect(&mTimerCapture,SIGNAL(timeout()),
          this, SLOT(capture()));
  connect(&mTimerConverter,SIGNAL(timeout()),
          this, SLOT(convert()));
  mTimerCapture.start(100);
  mTimerConverter.start(250);
}

CvCam::CvCam(int camId, QObject *parent)
{
  mCapture = NULL;
  connect(&mTimerCapture,SIGNAL(timeout()),
          this, SLOT(capture()));
  connect(&mTimerConverter,SIGNAL(timeout()),
          this, SLOT(convert()));
  init(camId);
  mTimerCapture.start(100);
  mTimerConverter.start(250);
}

CvCam::~CvCam()
{
  if (mCapture)
    cvReleaseCapture(&mCapture);
  mCapture = NULL; // vermutlich doppelt..
}

void CvCam::init(int camId)
{
  if (mCapture)
    cvReleaseCapture(&mCapture);
  if (camId >= 0)
    mCapture = cvCaptureFromCAM(camId);
}

void CvCam::capture()
{
  if (!mCapture)
    return;

  mFrame = cvQueryFrame(mCapture);
  Q_ASSERT(mFrame);
}

void CvCam::convert()
{
  if (!mCapture)
    return;

  Q_ASSERT(mFrame);

  QImage img((uchar*)mFrame->imageData, 
            mFrame->width, 
            mFrame->height, 
            QImage::Format_RGB888);
  emit frame(img);
  QPixmap pxe = QPixmap::fromImage(img);
  emit frame(pxe);

  /*
  switch(mFrame->depth) {
    case IPL_DEPTH_8U  : qDebug() << "8U"; break;
    case IPL_DEPTH_8S  : qDebug() << "8S"; break;
    case IPL_DEPTH_16U : qDebug() << "16U"; break;
    case IPL_DEPTH_16S : qDebug() << "16S"; break;
    case IPL_DEPTH_32S : qDebug() << "32S"; break;
    case IPL_DEPTH_32F : qDebug() << "32F"; break;
    case IPL_DEPTH_32F : qDebug() << "32F"; break;
    case IPL_DEPTH_64F : qDebug() << "64F"; break;
  }
  */
}
